<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.1.2">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.1.2">


  <link rel="mask-icon" href="/images/logo.svg?v=7.1.2" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '7.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="普通的线性回归，在计算总样本误差即损失值时，对所有训练样本一视同仁，因此极少数”坏”样本会使得预测模型偏离于大多数好样本所遵循的规则，影响模型的预测精度。">
<meta name="keywords" content="AI进阶,机器学习">
<meta property="og:type" content="article">
<meta property="og:title" content="机器学习-回归问题">
<meta property="og:url" content="https://rencheng.cc/2019/02/20/ml/回归/index.html">
<meta property="og:site_name" content="PHOENIX&#39;s Blog">
<meta property="og:description" content="普通的线性回归，在计算总样本误差即损失值时，对所有训练样本一视同仁，因此极少数”坏”样本会使得预测模型偏离于大多数好样本所遵循的规则，影响模型的预测精度。">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-02-20T06:51:41.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="机器学习-回归问题">
<meta name="twitter:description" content="普通的线性回归，在计算总样本误差即损失值时，对所有训练样本一视同仁，因此极少数”坏”样本会使得预测模型偏离于大多数好样本所遵循的规则，影响模型的预测精度。">



  <link rel="alternate" href="/atom.xml" title="PHOENIX's Blog" type="application/atom+xml">



  
  
  <link rel="canonical" href="https://rencheng.cc/2019/02/20/ml/回归/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>机器学习-回归问题 | PHOENIX's Blog</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">PHOENIX's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">Enjoy the journey of life</h1>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://rencheng.cc/2019/02/20/ml/回归/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="任成">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.JPG">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="PHOENIX's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">机器学习-回归问题

              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-02-20 14:51:41" itemprop="dateCreated datePublished" datetime="2019-02-20T14:51:41+08:00">2019-02-20</time>
            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/教程/" itemprop="url" rel="index"><span itemprop="name">教程</span></a></span>

                
                
              
            </span>
          

          
            
            
          

          
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                <span title="本文字数">11k</span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>普通的线性回归，在计算总样本误差即损失值时，对所有训练样本一视同仁，因此极少数”坏”样本会使得预测模型偏离于大多数好样本所遵循的规则，影响模型的预测精度。<br><a id="more"></a></p>
<h2 id="线性回归"><a href="#线性回归" class="headerlink" title="线性回归"></a>线性回归</h2><p>import sklearn.linear_model as lm<br>创建学习模型对象：model=lm.LinearRegression()<br>训练学习模型对象：model.fit(x, y) # [x, y]-BGD-&gt;[w0, w1]<br>预测给定输入的输出：pred_y = model.predict(pred_x)<br><figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pickle</span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.linear_model <span class="keyword">as</span> lm</span><br><span class="line"><span class="keyword">import</span> sklearn.metrics <span class="keyword">as</span> sm</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">x, y = [], []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/single.txt'</span>, <span class="string">'r'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data = [float(substr) <span class="keyword">for</span> substr</span><br><span class="line">			<span class="keyword">in</span> line.split(<span class="string">','</span>)]</span><br><span class="line">		x.append(data[:<span class="number">-1</span>])</span><br><span class="line">		y.append(data[<span class="number">-1</span>])</span><br><span class="line">x = np.array(x)</span><br><span class="line">y = np.array(y)</span><br><span class="line"><span class="comment"># 创建线性回归器</span></span><br><span class="line">model = lm.LinearRegression()</span><br><span class="line"><span class="comment"># 训练线性回归器</span></span><br><span class="line">model.fit(x, y) <span class="comment"># 根据梯度下降算法寻找最优的模型参数</span></span><br><span class="line"><span class="comment"># 测试线性回归器</span></span><br><span class="line">pred_y = model.predict(x)</span><br><span class="line"><span class="keyword">for</span> train, pred <span class="keyword">in</span> zip(y, pred_y):</span><br><span class="line">	print(train, <span class="string">'-&gt;'</span>, pred)</span><br><span class="line"><span class="comment"># 平均绝对值误差：mean(|y-y'|)</span></span><br><span class="line">print(sm.mean_absolute_error(y, pred_y))</span><br><span class="line"><span class="comment"># 平均平方误差：mean((y-y')^2)</span></span><br><span class="line">print(sm.mean_squared_error(y, pred_y))</span><br><span class="line"><span class="comment"># 中位数绝对值误差：median(|y-y'|)</span></span><br><span class="line">print(sm.median_absolute_error(y, pred_y))</span><br><span class="line"><span class="comment"># 协方差误差分值：[-1, 1]</span></span><br><span class="line">print(sm.explained_variance_score(y, pred_y))</span><br><span class="line"><span class="comment"># R2分值：综合以上所有指标得到的综合评价，[0, 1]</span></span><br><span class="line">print(sm.r2_score(y, pred_y))</span><br><span class="line"><span class="comment"># 保存训练好的模型</span></span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/linear.pkl'</span>, <span class="string">'wb'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	pickle.dump(model, f)</span><br><span class="line">mp.figure(<span class="string">'Linear Regression'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'Linear Regression'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.grid(linestyle=<span class="string">':'</span>)</span><br><span class="line">mp.scatter(x, y, c=<span class="string">'dodgerblue'</span>, alpha=<span class="number">0.75</span>,</span><br><span class="line">	s=<span class="number">60</span>, label=<span class="string">'Sample'</span>)</span><br><span class="line">sorted_indices = x.T[<span class="number">0</span>].argsort()</span><br><span class="line">mp.plot(x[sorted_indices], pred_y[sorted_indices],</span><br><span class="line">	c=<span class="string">'orangered'</span>, label=<span class="string">'Regression'</span>)</span><br><span class="line">mp.legend()</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure></p>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pickle</span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.linear_model <span class="keyword">as</span> lm</span><br><span class="line"><span class="keyword">import</span> sklearn.metrics <span class="keyword">as</span> sm</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">x, y = [], []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/single.txt'</span>, <span class="string">'r'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data = [float(substr) <span class="keyword">for</span> substr</span><br><span class="line">			<span class="keyword">in</span> line.split(<span class="string">','</span>)]</span><br><span class="line">		x.append(data[:<span class="number">-1</span>])</span><br><span class="line">		y.append(data[<span class="number">-1</span>])</span><br><span class="line">x = np.array(x)</span><br><span class="line">y = np.array(y)</span><br><span class="line"><span class="comment"># 从文件中加载模型</span></span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/linear.pkl'</span>, <span class="string">'rb'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	model = pickle.load(f)</span><br><span class="line"><span class="comment"># 测试线性回归器</span></span><br><span class="line">pred_y = model.predict(x)</span><br><span class="line"><span class="keyword">for</span> train, pred <span class="keyword">in</span> zip(y, pred_y):</span><br><span class="line">	print(train, <span class="string">'-&gt;'</span>, pred)</span><br><span class="line"><span class="comment"># 平均绝对值误差：mean(|y-y'|)</span></span><br><span class="line">print(sm.mean_absolute_error(y, pred_y))</span><br><span class="line"><span class="comment"># 平均平方误差：mean((y-y')^2)</span></span><br><span class="line">print(sm.mean_squared_error(y, pred_y))</span><br><span class="line"><span class="comment"># 中位数绝对值误差：median(|y-y'|)</span></span><br><span class="line">print(sm.median_absolute_error(y, pred_y))</span><br><span class="line"><span class="comment"># 协方差误差分值：[-1, 1]</span></span><br><span class="line">print(sm.explained_variance_score(y, pred_y))</span><br><span class="line"><span class="comment"># R2分值：综合以上所有指标得到的综合评价，[0, 1]</span></span><br><span class="line">print(sm.r2_score(y, pred_y))</span><br><span class="line">mp.figure(<span class="string">'Linear Regression'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'Linear Regression'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.grid(linestyle=<span class="string">':'</span>)</span><br><span class="line">mp.scatter(x, y, c=<span class="string">'dodgerblue'</span>, alpha=<span class="number">0.75</span>,</span><br><span class="line">	s=<span class="number">60</span>, label=<span class="string">'Sample'</span>)</span><br><span class="line">sorted_indices = x.T[<span class="number">0</span>].argsort()</span><br><span class="line">mp.plot(x[sorted_indices], pred_y[sorted_indices],</span><br><span class="line">	c=<span class="string">'orangered'</span>, label=<span class="string">'Regression'</span>)</span><br><span class="line">mp.legend()</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<h2 id="岭回归"><a href="#岭回归" class="headerlink" title="岭回归"></a>岭回归</h2><p>普通的线性回归，在计算总样本误差即损失值时，对所有训练样本一视同仁，因此极少数”坏”样本会使得预测模型偏离于大多数好样本所遵循的规则，影响模型的预测精度。岭回归就是在线性回归的基础之上，为每个训练样本分配不同的权重，越是能够反应一般规律的大多数好样本所得到的权重越大，而极少数偏离于一般规律的坏样本则只能获得较低的权重，从而使得最终的预测模型尽可能偏向于多数好样本，而弱化少数坏样本对模型的影响。<br>因此：超参数，人为给定<br>model = lm.Ridge(正则强度/惩罚力度)<br>正则强度/惩罚力度：[0, oo)<br>正则强度越小，权重差异就越小，0表示无差异，等同线性回归<br><figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.linear_model <span class="keyword">as</span> lm</span><br><span class="line"><span class="keyword">import</span> sklearn.metrics <span class="keyword">as</span> sm</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">x, y = [], []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/abnormal.txt'</span>, <span class="string">'r'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data = [float(substr) <span class="keyword">for</span> substr</span><br><span class="line">			<span class="keyword">in</span> line.split(<span class="string">','</span>)]</span><br><span class="line">		x.append(data[:<span class="number">-1</span>])</span><br><span class="line">		y.append(data[<span class="number">-1</span>])</span><br><span class="line">x = np.array(x)</span><br><span class="line">y = np.array(y)</span><br><span class="line"><span class="comment"># 创建线性回归器</span></span><br><span class="line">model1 = lm.LinearRegression()</span><br><span class="line"><span class="comment"># 训练线性回归器</span></span><br><span class="line">model1.fit(x, y) <span class="comment"># 根据梯度下降算法寻找最优的模型参数</span></span><br><span class="line"><span class="comment"># 测试线性回归器</span></span><br><span class="line">pred_y1 = model1.predict(x)</span><br><span class="line"><span class="comment"># 线性回归的R2分值</span></span><br><span class="line">print(sm.r2_score(y, pred_y1))</span><br><span class="line"><span class="comment"># 创建岭回归器</span></span><br><span class="line">model2 = lm.Ridge(<span class="number">250</span>)</span><br><span class="line"><span class="comment"># 训练岭回归器</span></span><br><span class="line">model2.fit(x, y) <span class="comment"># 通过差异化权重削弱异常样本的影响</span></span><br><span class="line"><span class="comment"># 测试岭回归器</span></span><br><span class="line">pred_y2 = model2.predict(x)</span><br><span class="line"><span class="comment"># 岭回归的R2分值</span></span><br><span class="line">print(sm.r2_score(y, pred_y2))</span><br><span class="line">mp.figure(<span class="string">'Linear &amp; Ridge Regression'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'Linear &amp; Ridge Regression'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.grid(linestyle=<span class="string">':'</span>)</span><br><span class="line">mp.scatter(x, y, c=<span class="string">'dodgerblue'</span>, alpha=<span class="number">0.75</span>,</span><br><span class="line">	s=<span class="number">60</span>, label=<span class="string">'Sample'</span>)</span><br><span class="line">sorted_indices = x.T[<span class="number">0</span>].argsort()</span><br><span class="line">mp.plot(x[sorted_indices], pred_y1[sorted_indices],</span><br><span class="line">	c=<span class="string">'orangered'</span>, label=<span class="string">'Linear'</span>)</span><br><span class="line">mp.plot(x[sorted_indices], pred_y2[sorted_indices],</span><br><span class="line">	c=<span class="string">'limegreen'</span>, label=<span class="string">'Ridge'</span>)</span><br><span class="line">mp.legend()</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure></p>
<h2 id="多项式回归"><a href="#多项式回归" class="headerlink" title="多项式回归"></a>多项式回归</h2><p>$y = w_1 + w_1x + w_2x^2 + w_3x^3 + … + w_nx^n$<br>$loss = Loss(w_0, w_1, …, w_n)$<br>$y = w_0 + w_1 \times 1 + w_2 \times 2 + w_3 \times 3 + … + w_n \times n$<br>$x_1 -&gt; x_1, x_2, x_3, …, x_n$<br>$\Downarrow$<br>x1-&gt;多项式特征扩展-x1,x2,x3,…,xn-&gt;线性回归-&gt;w0~wn<br>$\Downarrow$<br>管线</p>
<p>import sklearn.pipeline as pl<br>import sklearn.preprocessing as sp<br>多项式特征扩展器=sp.PolynomialFeatures(n=最高次幂)<br>线性回归器=lm.LinearRegression()<br>管线模型=pl.make_pipeline(多项式特征扩展器,线性回归器)<br>管线模型.fit(x,y) # [x,y]-BGD-&gt;[w0,w1,w2,w3,…,wn]<br>管线模型.predict(x)-&gt;pred_y<br><strong>_欠拟合_</strong>：过于简单的模型，或者训练集的规模过小，导致模型无法真实地反应输入和输出之间的规律，出现训练集和测试集的评估分值都比较低的现象。可以通过增加模型的复杂度，或者增加训练集的规模，提高模型的拟合度，优化其性能。<br><strong>_过拟合_</strong>：过于复杂的模型，或者特征数过多，大致模型失去足够的一般性，即太过于倾向训练数据，反而对训练集以外的其它样本的预测性能大幅下降。可以减少特征数，或者降低模型的复杂度，在训练集和测试集的拟合程度上寻求一个折衷，提高模型的泛化能力。<br><figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.pipeline <span class="keyword">as</span> pl</span><br><span class="line"><span class="keyword">import</span> sklearn.preprocessing <span class="keyword">as</span> sp</span><br><span class="line"><span class="keyword">import</span> sklearn.linear_model <span class="keyword">as</span> lm</span><br><span class="line"><span class="keyword">import</span> sklearn.metrics <span class="keyword">as</span> sm</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">train_x, train_y = [], []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/single.txt'</span>, <span class="string">'r'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data = [float(substr) <span class="keyword">for</span> substr</span><br><span class="line">			<span class="keyword">in</span> line.split(<span class="string">','</span>)]</span><br><span class="line">		train_x.append(data[:<span class="number">-1</span>])</span><br><span class="line">		train_y.append(data[<span class="number">-1</span>])</span><br><span class="line">train_x = np.array(train_x)</span><br><span class="line">train_y = np.array(train_y)</span><br><span class="line">model = pl.make_pipeline(sp.PolynomialFeatures(<span class="number">10</span>),</span><br><span class="line">	lm.LinearRegression())</span><br><span class="line">model.fit(train_x, train_y)</span><br><span class="line">pred_train_y = model.predict(train_x)</span><br><span class="line">print(sm.r2_score(train_y, pred_train_y))</span><br><span class="line">test_x = np.linspace(train_x.min(),</span><br><span class="line">	train_x.max(), <span class="number">1000</span>)[:, np.newaxis]</span><br><span class="line">pred_test_y = model.predict(test_x)</span><br><span class="line">mp.figure(<span class="string">'Polynomial Regression'</span>,</span><br><span class="line">	facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'Polynomial Regression'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.grid(linestyle=<span class="string">':'</span>)</span><br><span class="line">mp.scatter(train_x, train_y, c=<span class="string">'dodgerblue'</span>,</span><br><span class="line">	alpha=<span class="number">0.75</span>, s=<span class="number">60</span>, label=<span class="string">'Sample'</span>)</span><br><span class="line">mp.plot(test_x, pred_test_y, c=<span class="string">'orangered'</span>,</span><br><span class="line">	label=<span class="string">'Regression'</span>)</span><br><span class="line">mp.legend()</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure></p>
<h2 id="决策树"><a href="#决策树" class="headerlink" title="决策树"></a>决策树</h2><p>既可用于解决回归问题，也可用于解决分类问题。</p>
<ol>
<li><p>相似的输入必会产生相似的输出</p>
 <figure class="highlight lsl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">年龄：<span class="number">0</span>-青年，<span class="number">1</span>-中年，<span class="number">2</span>-老年</span><br><span class="line">学历：<span class="number">0</span>-大专，<span class="number">1</span>-大本，<span class="number">2</span>-硕士，<span class="number">3</span>-博士</span><br><span class="line">资历：<span class="number">0</span>-小白，<span class="number">1</span>-小牛，<span class="number">2</span>-大牛，<span class="number">3</span>-骨灰</span><br><span class="line">性别：<span class="number">0</span>-女性，<span class="number">1</span>-男性</span><br><span class="line">等级：<span class="number">0</span>-低收入，<span class="number">1</span>-中等收入，<span class="number">2</span>-高收入</span><br><span class="line"></span><br><span class="line">年龄  学历  资历  性别  月薪      等级</span><br><span class="line">  <span class="number">0</span>       <span class="number">1</span>       <span class="number">0</span>       <span class="number">1</span>    <span class="number">6000</span>       <span class="number">0</span></span><br><span class="line">  <span class="number">0</span>       <span class="number">0</span>       <span class="number">1</span>       <span class="number">1</span>    <span class="number">7000</span>       <span class="number">1</span></span><br><span class="line">  <span class="number">1</span>       <span class="number">2</span>       <span class="number">2</span>       <span class="number">1</span>    <span class="number">10000</span>      <span class="number">2</span></span><br><span class="line">--&gt;</span><br><span class="line">  <span class="number">0</span>      <span class="number">0</span>       <span class="number">1</span>        <span class="number">1</span>    对输出取平均/对输出做投票</span><br></pre></td></tr></table></figure>
</li>
</ol>
<ol>
<li>构建树状模型提高对相似输入的检索性能<br>依次选取总样本空间中的每一个特征作为划分子表的依据，将样本矩阵划分为若干层级的多个子矩阵，每一个层级对应一个特征，组成树状结构。预测时，根据待预测样本的每个特征值，找到与之对应的叶级子表，将该子表的输出按照平均或者投票的方式计算预测值。</li>
<li>优先选择对输出影响最大的部分特征划分子表<br>根据按照某个特征划分子表前后，其信息熵或基尼不纯度的减少量来判断该特征对输出的影响，信息熵或基尼不纯度减少量越大的特征，对输出的影响也越大，越应该优先作为子表划分的依据。</li>
<li><p>集成算法</p>
<ol>
<li>自助聚合：每次从总样本空间中随机抽取一部分样本构建决策树，这样共构建B棵决策树</li>
<li>随机森林：每次从总样本空间中随机抽取一部分样本及特征构建决策树，这样共构建B棵决策树</li>
<li><p>正向激励：为样本空间中的每个样本分配初始权重，构建第一颗决策树，针对训练集中预测错误的样本，提升其权重，再构建第二棵决策树，以此类推，共构建B棵权重各不相同的决策树</p>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.datasets <span class="keyword">as</span> sd</span><br><span class="line"><span class="keyword">import</span> sklearn.utils <span class="keyword">as</span> su</span><br><span class="line"><span class="keyword">import</span> sklearn.tree <span class="keyword">as</span> st</span><br><span class="line"><span class="keyword">import</span> sklearn.ensemble <span class="keyword">as</span> se</span><br><span class="line"><span class="keyword">import</span> sklearn.metrics <span class="keyword">as</span> sm</span><br><span class="line">boston = sd.load_boston()</span><br><span class="line">x, y = su.shuffle(boston.data, boston.target,</span><br><span class="line">	random_state=<span class="number">7</span>)</span><br><span class="line">train_size = int(len(x) * <span class="number">0.8</span>)</span><br><span class="line">train_x, test_x, train_y, test_y = \</span><br><span class="line">	x[:train_size], x[train_size:], \</span><br><span class="line">	y[:train_size], y[train_size:]</span><br><span class="line"><span class="comment"># 决策树回归器</span></span><br><span class="line">model = st.DecisionTreeRegressor(max_depth=<span class="number">4</span>)</span><br><span class="line">model.fit(train_x, train_y)</span><br><span class="line">pred_test_y = model.predict(test_x)</span><br><span class="line">print(sm.r2_score(test_y, pred_test_y))</span><br><span class="line"><span class="comment"># 正向激励集成决策树回归器</span></span><br><span class="line">model = se.AdaBoostRegressor(</span><br><span class="line">	st.DecisionTreeRegressor(max_depth=<span class="number">4</span>),</span><br><span class="line">	n_estimators=<span class="number">400</span>, random_state=<span class="number">7</span>)</span><br><span class="line">model.fit(train_x, train_y)</span><br><span class="line">pred_test_y = model.predict(test_x)</span><br><span class="line">print(sm.r2_score(test_y, pred_test_y))</span><br></pre></td></tr></table></figure>
</li>
</ol>
</li>
<li><p>特征重要性<br>决策树模型在确定子表划分依据的过程中，会计算按照每个特征划分子表所引起的信息熵或基尼不纯度减少量，从业务上看该指标即体现了，每个特征对输出的影响力度。<br>model = …<br>model.fit(…)<br>model.feature_importances_</p>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.datasets <span class="keyword">as</span> sd</span><br><span class="line"><span class="keyword">import</span> sklearn.utils <span class="keyword">as</span> su</span><br><span class="line"><span class="keyword">import</span> sklearn.tree <span class="keyword">as</span> st</span><br><span class="line"><span class="keyword">import</span> sklearn.ensemble <span class="keyword">as</span> se</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">boston = sd.load_boston()</span><br><span class="line">fn = boston.feature_names</span><br><span class="line">x, y = su.shuffle(boston.data, boston.target,</span><br><span class="line">	random_state=<span class="number">7</span>)</span><br><span class="line">train_size = int(len(x) * <span class="number">0.8</span>)</span><br><span class="line">train_x, test_x, train_y, test_y = \</span><br><span class="line">	x[:train_size], x[train_size:], \</span><br><span class="line">	y[:train_size], y[train_size:]</span><br><span class="line"><span class="comment"># 正向激励集成决策树回归器</span></span><br><span class="line">model = se.AdaBoostRegressor(</span><br><span class="line">	st.DecisionTreeRegressor(max_depth=<span class="number">4</span>),</span><br><span class="line">	n_estimators=<span class="number">400</span>, random_state=<span class="number">7</span>)</span><br><span class="line">model.fit(train_x, train_y)</span><br><span class="line">fi = model.feature_importances_</span><br><span class="line"><span class="keyword">for</span> n, i <span class="keyword">in</span> zip(fn, fi):</span><br><span class="line">	print(<span class="string">'&#123;:&gt;10&#125; : &#123;:.4f&#125;'</span>.format(n, i))</span><br><span class="line">mp.figure(<span class="string">'Feature Importance'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'Feature Importance'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'Feature'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'Importance'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.grid(axis=<span class="string">'y'</span>, linestyle=<span class="string">':'</span>)</span><br><span class="line">sorted_indices = fi.argsort()[::<span class="number">-1</span>]</span><br><span class="line">pos = np.arange(sorted_indices.size)</span><br><span class="line">mp.bar(pos, fi[sorted_indices], facecolor=<span class="string">'lightcoral'</span>,</span><br><span class="line">	edgecolor=<span class="string">'indianred'</span>)</span><br><span class="line">mp.xticks(pos, fn[sorted_indices], rotation=<span class="number">30</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>特征重要性与模型的算法有关，还与数据的粒度有关。<br><figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> csv</span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.utils <span class="keyword">as</span> su</span><br><span class="line"><span class="keyword">import</span> sklearn.ensemble <span class="keyword">as</span> se</span><br><span class="line"><span class="keyword">import</span> sklearn.metrics <span class="keyword">as</span> sm</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/bike_day.csv'</span>, <span class="string">'r'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	reader = csv.reader(f)</span><br><span class="line">	x, y = [], []</span><br><span class="line">	<span class="keyword">for</span> row <span class="keyword">in</span> reader:</span><br><span class="line">		x.append(row[<span class="number">2</span>:<span class="number">13</span>])</span><br><span class="line">		y.append(row[<span class="number">-1</span>])</span><br><span class="line">fn_dy = np.array(x[<span class="number">0</span>])</span><br><span class="line">x = np.array(x[<span class="number">1</span>:], dtype=float)</span><br><span class="line">y = np.array(y[<span class="number">1</span>:], dtype=float)</span><br><span class="line">x, y = su.shuffle(x, y, random_state=<span class="number">7</span>)</span><br><span class="line">train_size = int(len(x) * <span class="number">0.9</span>)</span><br><span class="line">train_x, test_x, train_y, test_y = \</span><br><span class="line">	x[:train_size], x[train_size:], \</span><br><span class="line">	y[:train_size], y[train_size:]</span><br><span class="line"><span class="comment"># 随机森林集成决策树回归器</span></span><br><span class="line">model = se.RandomForestRegressor(</span><br><span class="line">	max_depth=<span class="number">10</span>, n_estimators=<span class="number">1000</span>,</span><br><span class="line">	min_samples_split=<span class="number">2</span>)</span><br><span class="line">model.fit(train_x, train_y)</span><br><span class="line">fi_dy = model.feature_importances_</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/bike_hour.csv'</span>, <span class="string">'r'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	reader = csv.reader(f)</span><br><span class="line">	x, y = [], []</span><br><span class="line">	<span class="keyword">for</span> row <span class="keyword">in</span> reader:</span><br><span class="line">		x.append(row[<span class="number">2</span>:<span class="number">14</span>])</span><br><span class="line">		y.append(row[<span class="number">-1</span>])</span><br><span class="line">fn_hr = np.array(x[<span class="number">0</span>])</span><br><span class="line">x = np.array(x[<span class="number">1</span>:], dtype=float)</span><br><span class="line">y = np.array(y[<span class="number">1</span>:], dtype=float)</span><br><span class="line">x, y = su.shuffle(x, y, random_state=<span class="number">7</span>)</span><br><span class="line">train_size = int(len(x) * <span class="number">0.9</span>)</span><br><span class="line">train_x, test_x, train_y, test_y = \</span><br><span class="line">	x[:train_size], x[train_size:], \</span><br><span class="line">	y[:train_size], y[train_size:]</span><br><span class="line"><span class="comment"># 随机森林集成决策树回归器</span></span><br><span class="line">model = se.RandomForestRegressor(</span><br><span class="line">	max_depth=<span class="number">10</span>, n_estimators=<span class="number">1000</span>,</span><br><span class="line">	min_samples_split=<span class="number">2</span>)</span><br><span class="line">model.fit(train_x, train_y)</span><br><span class="line">fi_hr = model.feature_importances_</span><br><span class="line">mp.figure(<span class="string">'Bike'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.subplot(<span class="number">211</span>)</span><br><span class="line">mp.title(<span class="string">'Day'</span>, fontsize=<span class="number">16</span>)</span><br><span class="line">mp.ylabel(<span class="string">'Importance'</span>, fontsize=<span class="number">12</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.grid(axis=<span class="string">'y'</span>, linestyle=<span class="string">':'</span>)</span><br><span class="line">sorted_indices = fi_dy.argsort()[::<span class="number">-1</span>]</span><br><span class="line">pos = np.arange(sorted_indices.size)</span><br><span class="line">mp.bar(pos, fi_dy[sorted_indices], facecolor=<span class="string">'deepskyblue'</span>,</span><br><span class="line">	edgecolor=<span class="string">'steelblue'</span>)</span><br><span class="line">mp.xticks(pos, fn_dy[sorted_indices], rotation=<span class="number">30</span>)</span><br><span class="line">mp.subplot(<span class="number">212</span>)</span><br><span class="line">mp.title(<span class="string">'Hour'</span>, fontsize=<span class="number">16</span>)</span><br><span class="line">mp.xlabel(<span class="string">'Feature'</span>, fontsize=<span class="number">12</span>)</span><br><span class="line">mp.ylabel(<span class="string">'Importance'</span>, fontsize=<span class="number">12</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.grid(axis=<span class="string">'y'</span>, linestyle=<span class="string">':'</span>)</span><br><span class="line">sorted_indices = fi_hr.argsort()[::<span class="number">-1</span>]</span><br><span class="line">pos = np.arange(sorted_indices.size)</span><br><span class="line">mp.bar(pos, fi_hr[sorted_indices], facecolor=<span class="string">'lightcoral'</span>,</span><br><span class="line">	edgecolor=<span class="string">'indianred'</span>)</span><br><span class="line">mp.xticks(pos, fn_hr[sorted_indices], rotation=<span class="number">30</span>)</span><br><span class="line">mp.tight_layout()</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure></p>
<blockquote>
<p>对于回归问题，模型关注的是回归曲线，该曲线反映了输入数据和输出数据之间的函数关系。<br>对于分类问题，模型关注的是分类边界，边界线反映了不同类别之间的划分依据。</p>
</blockquote>

      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/AI进阶/" rel="tag"># AI进阶</a>
          
            <a href="/tags/机器学习/" rel="tag"># 机器学习</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/02/12/ml/梯度下降/" rel="next" title="机器学习-梯度下降算法">
                <i class="fa fa-chevron-left"></i> 机器学习-梯度下降算法
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/02/22/ml/分类/" rel="prev" title="机器学习-分类问题">
                机器学习-分类问题 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.JPG" alt="任成">
            
              <p class="site-author-name" itemprop="name">任成</p>
              <div class="site-description motion-element" itemprop="description"></div>
          </div>

          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL0NvZGVyQ3VydmU=" title="GitHub &rarr; https://github.com/CoderCurve"><i class="fa fa-fw fa-github"></i>GitHub</span>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="bWFpbHRvOnJlbmNoZW5nMTFAaWNsb3VkLmNvbQ==" title="E-Mail &rarr; mailto:rencheng11@icloud.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</span>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#线性回归"><span class="nav-number">1.</span> <span class="nav-text">线性回归</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#岭回归"><span class="nav-number">2.</span> <span class="nav-text">岭回归</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#多项式回归"><span class="nav-number">3.</span> <span class="nav-text">多项式回归</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#决策树"><span class="nav-number">4.</span> <span class="nav-text">决策树</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">  <span class="exturl" data-url="aHR0cDovL3d3dy5iZWlhbi5taWl0Lmdvdi5jbg==">京ICP备18001214号 </span>&copy; 2014 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">任成</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
    <span title="站点总字数">277k</span>
  

  
</div>









        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/utils.js?v=7.1.2"></script>

  <script src="/js/motion.js?v=7.1.2"></script>



  
  


  <script src="/js/affix.js?v=7.1.2"></script>

  <script src="/js/schemes/pisces.js?v=7.1.2"></script>



  
  <script src="/js/scrollspy.js?v=7.1.2"></script>
<script src="/js/post-details.js?v=7.1.2"></script>



  


  <script src="/js/next-boot.js?v=7.1.2"></script>


  

  
  <script src="/js/exturl.js?v=7.1.2"></script>


  

  


  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
  

  
  

  


  

  
<script>
if ($('body').find('pre.mermaid').length) {
  $.ajax({
    type: 'GET',
    url: '//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js',
    dataType: 'script',
    cache: true,
    success: function() {
      mermaid.initialize({
        theme: 'forest',
        logLevel: 3,
        flowchart: { curve: 'linear' },
        gantt: { axisFormat: '%m/%d/%Y' },
        sequence: { actorMargin: 50 }
      });
    }
  });
}
</script>


  

  

  

  

  

  

  

  

  

</body>
</html>
